package com.ytz.mysecurity.config;

import com.ytz.mysecurity.handler.MyLoginFailureHandler;
import com.ytz.mysecurity.handler.MyLoginSuccessHandler;
import com.ytz.mysecurity.handler.MyLogoutSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

/**
 * 12/22  23:10
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PersistentTokenRepository repository;
    /*@Bean
    public UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        UserDetails user1 = User.withUsername("baizhan").password("123").authorities("admin").build();
        UserDetails user2 = User.withUsername("sxt").password("456").authorities("admin").build();
        manager.createUser(user1);
        manager.createUser(user2);
        return manager;
    }*/

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 自定义表单登录
        http.formLogin()
                .loginPage("/login.html") // 自定义登录页面
                .usernameParameter("username") // 表单中的用户名项
                .passwordParameter("password") // 表单中的密码项
                .loginProcessingUrl("/login") // 登录路径，表单向该路径提交，提交后自动执行UserDetailsService的方法
                /*.successForwardUrl("/main")*/ //登录成功后跳转的路径
                .successHandler(new MyLoginSuccessHandler())
                /*.failureForwardUrl("/fail");*/ //登录失败后跳转的路径
                .failureHandler(new MyLoginFailureHandler());
        // 需要认证的资源
        http.authorizeRequests()
                .antMatchers("/login.html").permitAll() //登录页不需要认证
                .antMatchers("/fail").permitAll()
               /* .antMatchers("/reportform/find").hasAnyAuthority("/reportform/find") // 给资源配置需要的权限
                .antMatchers("/salary/find").hasAnyAuthority("/salary/find")
                .antMatchers("/staff/find").hasAnyAuthority("/staff/find")*/
                .anyRequest().authenticated(); //其余所有请求都需要认证
        /* .anyRequest().access("@myAuthorizationService.hasPermission(request,authentication)");*/
// 退出登录配置
        http.logout()
                .logoutUrl("/logout") // 退出登录路径
                /*.logoutSuccessUrl("/login.html")*/ // 退出登录后跳转的路径
                .logoutSuccessHandler(new MyLogoutSuccessHandler())
                .clearAuthentication(true) //清除认证状态，默认为true
                .invalidateHttpSession(true); // 销毁HttpSession对象，默认为true
// 记住我配置
        http.rememberMe()
                .userDetailsService(userDetailsService)//登录逻辑交给哪个对象
                .tokenRepository(repository) //持久层对象
                .tokenValiditySeconds(30); //保存时间，单位：秒

        //关闭csrf防护
        http.csrf().disable();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 静态资源放行
        web.ignoring().antMatchers("/css/**");
    }
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
